/**
 * email.js file;
 * company:junqitecch
 * author:xuzuiotao
 * request from the http body throght post method
 */

var http=require('http');

var  consts  = require('../consts');
var smsmsg=require("../db/mphonemsg");
var iconv=require('iconv-lite');
var encoding = require('encoding');

var users=require('../db/users');
//type 20 normal msg
var SMS_URL='http://127.0.0.1:8025/wssmsg/msg/send?type=/TYPE/&msg=/CONTENT/&phone=/PHONE/';

//ios
var  GETTUI_URL='http://127.0.0.1:8025/getui//SYSTEM//pushtoSingle?token=/TOKEN/&msg=/CONTENT/';
//const WS_URL='http://127.0.0.1:8025/wssmsg/socket/send?uid=/UID/&msg=/CONTENT/';
var  WS_URL=consts.Url.MAIN+ '/wssmsg/socket/send?uid=/UID/&msg=/CONTENT/';
var  REDIS_URL=consts.Url.MAIN+ '/wssmsg/socket/redisSend?uid=/UID/&msg=/CONTENT/';
var  GETUI_URL=consts.Url.MAIN+ '/junqi/wssmsg/getui/androidSend?clentId=/UID/&msg=/CONTENT/';
var https = require("https");

/*
 * to:uid
 * content:utf8
 */
function sendWSMessage(to, content,auto, callback){
	content = encodeURIComponent(content);
	var url = WS_URL.replace('/UID/',to).replace('/CONTENT/',content);
	url += '&auto='+auto;
	console.log(url);

 	https.get(url,function(req,res){  
	    var html='';  
	    req.on('data',function(data){  
	        html+=data;  
	    });  
	    req.on('end',function(){  
	    	console.log('wss::'+html);
//	    	val=-1;
//	        console.info(html);  
//	        try {
//				val= Number(html);
//			} catch (e) {
//				console.log(e);
//			}
//			console.log(val);
//			if(val!=0){
//				response.errorCode=consts.Error.ERROR_GENERAL;
//				response.message=consts.Message.ERROR_SMS;
//			}else{
//				smsmsg.setSentTime(to,code4,null);
//				response.errorCode=consts.Error.NONE_ERROR;
//				response.message=consts.Message.OK_MESSAGE;
//			}
	        if(callback){
	        	callback();
	        }
	    }); 
	    req.on('error',function(e){
	    	console.log('wsserror::'+ JSON.stringify(e));
	    	
	    });
	    
	});
}


function sendRedisMessage(to, content,auto,extra, callback){
	content = encodeURIComponent(content);
	var url = REDIS_URL.replace('/UID/',to).replace('/CONTENT/',content);

	if(auto){
		url += '&auto='+auto;

	}else{
		url += '&auto='+0;

	}

	
	if(extra){
		url+= '&extra='+extra;
	}else{
		url+= '&extra='+0;
	}

	console.log(url);

 	https.get(url,function(req,res){  
	    var html='';  
	    req.on('data',function(data){  
	        html+=data;  
	    });  
	    req.on('end',function(){  
	    	console.log('wss::'+html);
//	    	val=-1;
//	        console.info(html);  
//	        try {
//				val= Number(html);
//			} catch (e) {
//				console.log(e);
//			}
//			console.log(val);
//			if(val!=0){
//				response.errorCode=consts.Error.ERROR_GENERAL;
//				response.message=consts.Message.ERROR_SMS;
//			}else{
//				smsmsg.setSentTime(to,code4,null);
//				response.errorCode=consts.Error.NONE_ERROR;
//				response.message=consts.Message.OK_MESSAGE;
//			}
	        if(callback){
	        	callback();
	        }
	    }); 
	    req.on('error',function(e){
	    	console.log('wsserror::'+ JSON.stringify(e));
	    	
	    });
	    
	});
}

/* 
 * system:ios android
 * to:getui token
 * content:utf8 
 * */
function sendGetuiMessage(conn,to, content,auto,extra,callback){  //to, content,conn,callback){

	console.log('sendGetuiMessage::'+ to);
	users.getPrintCID(conn,to,function(obj){
		
		if(obj ===null){
		
			if(callback){
	        	callback();
	        }
			return;
		}
		
		content = encodeURIComponent(content);
		var url = GETUI_URL.replace('/UID/',obj).replace('/CONTENT/',content);
		url += '&auto='+auto;
		if(extra !== null){
			url+= '&extra='+extra;
		}

		console.log(url);
		
		https.get(url,function(req,res){  
		    var html='';  
		    req.on('data',function(data){  
		        html+=data;  
		    });  
		    req.on('end',function(){  
		    	console.log('gettui::'+html);
//		    	val=-1;
//		        console.info(html);  
//		        try {
//					val= Number(html);
//				} catch (e) {
//					console.log(e);
//				}
//				console.log(val);
//				if(val!=0){
//					response.errorCode=consts.Error.ERROR_GENERAL;
//					response.message=consts.Message.ERROR_SMS;
//				}else{
//					smsmsg.setSentTime(to,code4,null);
//					response.errorCode=consts.Error.NONE_ERROR;
//					response.message=consts.Message.OK_MESSAGE;
//				}
		        if(callback){
		        	callback();
		        }
		    }); 
		    req.on('error',function(e){
		    	console.log('gettui::'+ JSON.stringify(e));
		    	if(callback){
		        	callback();
		        }
		    	
		    });
		    
		});
		
	});
 
}

/*
 * to:phone number;
 * content:utf8 
 */
function sendSMSMessage(to, content,callback){
	content = encodeURIComponent(content);
	var url = SMS_URL.replace('/TYPE/',20).replace('/CONTENT/',content).replace('/PHONE/',to);
	console.log(url);
 	http.get(url,function(req,res){  
	    var html='';  
	    req.on('data',function(data){  
	        html+=data;  
	    });  
	    req.on('end',function(){  
	    	console.log(html);
//	    	val=-1;
//	        console.info(html);  
//	        try {
//				val= Number(html);
//			} catch (e) {
//				console.log(e);
//			}
//			console.log(val);
//			if(val!=0){
//				response.errorCode=consts.Error.ERROR_GENERAL;
//				response.message=consts.Message.ERROR_SMS;
//			}else{
//				smsmsg.setSentTime(to,code4,null);
//				response.errorCode=consts.Error.NONE_ERROR;
//				response.message=consts.Message.OK_MESSAGE;
//			}
	        if(callback){
	        	callback();
	        }
	    });  
	    
	    req.on('error',function(e){
	    	console.log(JSON.stringify(e));
	    	
	    });
	    
	});  
}

function sendVeriCode(to,response,callback){

//	
//    ,ERROR_MOBILEPHONE_USED:'该手机号已被使用，请您换一个号码或者找回密码'
//        ,ERROR_EMAILADDRESS_USED:'该邮箱地址已被使用，请您换一个邮箱或者找回密码'
//        ,ERROR_MOBILEPHONE_UNFOUND:'该手机号未注册，请注册'
//        ,ERROR_EMAILADDRESS_UNFOUND:'该邮箱地址未被绑定，请先绑定或者换一个绑定的的邮箱' 
	
	var codenum= Math.floor(Math.random()*10000)+'';
	var code4 = ('0000'+codenum).substring(codenum.length);
	smsmsg.insert(to,code4,function(qerr){
		if(qerr){
			response.errorCode=consts.Error.ERROR_GENERAL;
			response.message=consts.Message.ERROR_SMS;
			if(callback){
				  callback();
			  }
		}else{
			var message= consts.Message.REG_VERICODE_URLEN.replace('/NUMBER/',code4);
			
			console.log('send sms');
			var url = hlURL.replace('/MOBILE/',to).replace('/LINKID/',new Date().getTime()+'').replace('/MESSAGE/',message);
			console.log(url);
			//get 请求外网  
			http.get(url,function(req,res){  
			    var html='';  
			    req.on('data',function(data){  
			        html+=data;  
			    });  
			    req.on('end',function(){  
			    	var val=-1;
			        console.info(html);  
			        try {
						val= Number(html);
					} catch (e) {
						console.log(e);
					}
					console.log(val);
					if(val!==0){
						response.errorCode=consts.Error.ERROR_GENERAL;
						response.message=consts.Message.ERROR_SMS;
					}else{
						smsmsg.setSentTime(to,code4,null);
						response.errorCode=consts.Error.NONE_ERROR;
						response.message=consts.Message.OK_MESSAGE;
					}
			        if(callback){
			        	callback();
			        }
			    });  
			});  

		}
	});
	
	
//	
//	codenum= Math.floor(Math.random()*10000)+'';
//	code4 = ('0000'+codenum).substring(codenum.length);
//	
//	emailmsg.insert(to,code4,function(qerr){
//		if(qerr){
//			response.errorCode=consts.Error.ERROR_GENERAL;
//			response.message=consts.Message.ERROR_EMAIL;
//			if(callback){
//				  callback();
//			  }
//		}else{
//			
//			// 开启一个 SMTP 连接池
//			var smtpTransport = nodemailer.createTransport("SMTP",{
//			  host: "smtp.163.com", // 主机
//			  secureConnection: true, // 使用 SSL
//			  port: 465, // SMTP 端口
//			  auth: {
//			    user: "xinmayoujiang8888@163.com", // 账号
//			    pass: "Xinma123" // 密码
//			  }
//			});
//
//			// 设置邮件内容
//			var mailOptions = {
//			  from: "信马由缰管理员<xinmayoujiang8888@163.com>", // 发件地址
//			  to: to, // 收件列表
//			  subject: "信马由缰邮件(重要)", // 标题
//			  html: '<b>'+consts.Message.REG_VERICODE.replace('/NUMBER/',code4)+'<br>' // html 内容
//			}
//
//			
//			// 发送邮件
//			smtpTransport.sendMail(mailOptions, function(error, res){
//			  if(error){
//			    console.log(error);
//				response.errorCode=consts.Error.ERROR_GENERAL;
//				response.message=consts.Message.ERROR_EMAIL;
//			  }else{
//				emailmsg.setSentTime(to,code4,null);
//			    console.log("Message sent: " + res.message);
//				response.errorCode=consts.Error.NONE_ERROR;
//				response.message=consts.Message.OK_MESSAGE;
//			  }
//			  if(callback){
//				  callback();
//			  }
//			  mailOptions = null;
//			  smtpTransport.close(); // 如果没用，关闭连接池
//			  smtpTransport = null;
//			});
//			
//		}
//	});
//	

}


function UrlEncode_BG(buff){   
	   var ret="";   
	   var bb = Buffer.from(' ');
	   var strSpecial='!/"#$%&\'()*+,/:;<=>?[]^`{|}~%';  
	   for(var i=0;i<buff.length;i++){   
	    var chr = buff[i];//charAt(i);   
	     //var c=str2asc(chr);  
	     var asc=buff[i];
	     var c =  Number(asc).toString(16);
	     if(parseInt("0x"+c) > 0x7f){   
	       ret+="%"+c.slice(0,2);//+"%"+c.slice(-2);   
	     }else{   
	       if(chr==" "){   
	         ret+="+";   
	       }else if(strSpecial.indexOf(chr)!=-1){   
	         ret+="%"+c.toString(16);   
	       }else {
	    	   bb[0] =chr;
	    	   bb.toString();
		       ret+=bb.toString();
	       }  
	     }   
	   }   
	   return ret;   
	
}   


function doSendMsg(tos,start, step,mess,callback){
	if(!Array.isArray(tos)){
		//tos=[tos];
		if(callback)callback();
		return;
	}
	if(start>=tos.length){
		if(callback)callback();
		return;
	}
	var end= ((start+step)<tos.length)?(start+step):tos.length;
	
	
	
	
	var phones=tos.slice(start,end);
	
	phones=phones.join(',');
	
	console.log(mess+ ':::'+start);
	var url = hlURL.replace('/MOBILE/',phones).replace('/LINKID/',new Date().getTime()+'').replace('/MESSAGE/',mess);
	console.log(url);
	//get 请求外网  
	http.get(url,function(req,res){  
//	    var html='';  
	    req.on('data',function(data){  
//	        html+=data;  
	    });  
	    req.on('end',function(){  
//	    	val=-1;
//	        console.info(html+'sms ok');  
//	        try {
//				val= Number(html);
//			} catch (e) {
//				console.log(e);
//			}
	    	doSendMsg(tos,start+step, step,mess,callback);
		
	    });  
	});  
	
	
}

function sendNormalMsg(to,mess,callback){
	
	
	var url = smsURL.replace('/TYPE/',20).replace('/CONTENT/',mess).replace('/PHONE/',to);
	
	
	
//	if(!Array.isArray(tos)){
//		tos=[tos];
//	}
//
//	str = '【信马由僵】'+ mess;
//	str2= encoding.convert(str, 'gb2312');
//	mess = UrlEncode_BG(str2);//'%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E6%98%AF8712');///mess);
//	
//	doSendMsg(tos, 0, 15, mess, callback);
//	
//	
////	to=tos.join(',');
////	
////	console.log(mess);
////	url = hlURL.replace('/MOBILE/',to).replace('/LINKID/',new Date().getTime()+'').replace('/MESSAGE/',mess);
////	console.log(url);
////	//get 请求外网  
////	http.get(url,function(req,res){  
////	    var html='';  
////	    req.on('data',function(data){  
////	        html+=data;  
////	    });  
////	    req.on('end',function(){  
////	    	val=-1;
////	        console.info(html+'sms ok');  
////	        try {
////				val= Number(html);
////			} catch (e) {
////				console.log(e);
////			}
////			console.log(val);
////		
////	    });  
////	});  
////	
//	return;
//	
//	
//	url='http://127.0.0.1:7080/send?mess=/%MESSAGE%/&mobile=/%MOBILES%/'
//		.replace('/%MESSAGE%/',mess).replace('/%MOBILES%/',to);
//		
//	
//	console.log(url);
//
//	http.get(url,function(req,res){  
//	    var html='';  
//	    req.on('data',function(data){  
//	        html+=data;  
//	    });  
//	    req.on('end',function(){  
//	    	val=-1;
//	        console.info(html+':::ok sms');  
//	        try {
//				val= Number(html);
//			} catch (e) {
//				console.log(e);
//			}
//			
//			console.log('ok');
//		
//	        if(callback){
//	        	callback();
//	        }
//	    });  
//	});  


}

module.exports = {
		sendVeriCode:sendVeriCode,
		sendNormalMsg:sendNormalMsg,
		sendSMSMessage:sendSMSMessage,
		sendGetuiMessage:sendGetuiMessage,
		sendWSMessage:sendWSMessage,
		sendRedisMessage:sendRedisMessage,
	};
